from kivy.core.window import Window
from kivy.graphics import Color
from kivy.resources import resource_find
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from nmjeditor.widgets.dvd import DVDBase, DVDBox, Thumbnail
from tempfile import mkdtemp
import os.path


class ScrollableMediaWall(ScrollView):
	def __init__(self, cols=5, image_size=(100, 150), callback=None, background_color=(1,1,1), *args, **kwargs):
		super(ScrollableMediaWall, self).__init__(*args, **kwargs)
		if background_color:
			with self.canvas:
				Color(*background_color)

		self.image_size = image_size
		self.callback = callback
		self.grid = GridLayout(
			cols=cols,
			spacing = 10,
			padding = 10,
			row_force_default=True, row_default_height=image_size[1],
			col_force_default=True, col_default_width=image_size[0],
			size_hint_y=None,
			size_hint_x=None,
		)
		#Make sure the height is such that there is something to scroll.
		Window.bind(width=self.reset_cols)
		self.grid.bind(minimum_height=self.grid.setter('height'))
		self.add_widget(self.grid)

	def reset_cols(self, *args, **kwargs):
		self.grid.cols = (Window.width / self.image_size[0]) - 1

	def add_images(self, *images):
		for image in images:
			btn = DVDBase(image, callback=self.callback, size=self.image_size)
			self.grid.add_widget(btn)
		self.reset_cols()

class ScrollableShowWall(ScrollableMediaWall):
	def add_shows(self, *shows):
		for show in shows:
			btn = DVDBox(show=show, callback=self.callback, size=self.image_size)
			self.grid.add_widget(btn)
		self.reset_cols()

class ScrollableFanartWall(ScrollableMediaWall):
	def __init__(self, cols=5, image_size=(150, 100), callback=None, background_color=(1,1,1), *args, **kwargs):
		super(ScrollableFanartWall, self).__init__(cols=cols, image_size=image_size, callback=callback, background_color=background_color, *args, **kwargs)

	def add_posters(self, *nmjimages):
		temp_directory = mkdtemp()
		for image in nmjimages:
			image_path = image.get_thumbnail(temp_directory)
			title = ""
			if not os.path.isfile(image_path):
				image_path = resource_find("default-poster.png")
				title = getattr(image, "title", "")
			btn = Thumbnail(image_path, text=title, metadata=image, callback=self.callback, size=self.image_size)
			self.grid.add_widget(btn)
			self.reset_cols()

class ScrollablePosterWall(ScrollableMediaWall):
	def add_posters(self, *nmjimages):
		temp_directory = mkdtemp()
		for image in nmjimages:
			image_path = image.get_thumbnail(temp_directory)
			title = ""
			if not os.path.isfile(image_path):
				image_path = resource_find("default-poster.png")
				title = getattr(image, "title", "")
			btn = DVDBase(image_path, text=title, metadata=image, callback=self.callback, size=self.image_size)
			self.grid.add_widget(btn)
			self.reset_cols()


